package com.yxt.qmgf.shop.ctrl;

import cn.hutool.extra.spring.SpringUtil;
import com.yxt.qmgf.shop.ctrl.ShopController;
import com.yxt.qmgf.shop.dao.ShopDao;
import com.yxt.qmgf.shop.vo.entity;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProductEditController {

    private static final Logger logger = LoggerFactory.getLogger(ProductEditController.class);

    @FXML
    private TextField nameField;

    @FXML
    private TextField descriptionField;

    @FXML
    private TextField priceField;

    @FXML
    private Button saveButton;

    @FXML
    private Button cancelButton;

    private entity product;
    private ShopController shopController;

    public void setProduct(entity product) {
        this.product = product;
        if (product == null) {
            throw new IllegalArgumentException("Product cannot be null");
        }
        if (product != null) {
            logger.info("product.getName(): {}", product.getName());
            if (nameField != null) {
                nameField.setText(product.getName());
            }
            if (descriptionField != null) {
                descriptionField.setText(product.getGongneng());
            }
            if (priceField != null) {
                priceField.setText(product.getPrice());
            }
        }
    }

    public void setShopController(ShopController shopController) {
        this.shopController = shopController;
    }

    @FXML
    private void saveProduct() {
        if (product == null) {
            product = new entity();
        }

        if (nameField != null) {
            product.setName(nameField.getText());
        }
        if (descriptionField != null) {
            product.setGongneng(descriptionField.getText());
        }
        if (priceField != null) {
            product.setPrice(priceField.getText());
        }

        ShopDao shopDao = SpringUtil.getBean(ShopDao.class);
        if (shopDao != null) {
            if (product.getId() == null) {
                product.setHave(0);
                shopDao.Insert(product);
            } else {
                shopDao.Update(product);
            }
        } else {
            logger.error("ShopDao is null");
        }

        if (saveButton != null) {
            Stage stage = (Stage) saveButton.getScene().getWindow();
            stage.close();
        }
    }

    @FXML
    private void cancel() {
        if (cancelButton != null) {
            Stage stage = (Stage) cancelButton.getScene().getWindow();
            stage.close();
        }
    }
}